﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient.Credentials
Imports System.Globalization
Imports System.Data.Services.Client

Public Class CloudTableClient
    Implements ICloudTableClient
    Private context As ITableServiceContext

    <CLSCompliant(False)>
    Public Sub New(ByVal context As ITableServiceContext)
        Me.context = context
    End Sub

    Public Sub CreateTable(ByVal tableName As String, ByVal callback As Action(Of CloudOperationResponse(Of String))) Implements ICloudTableClient.CreateTable
        Me.context.AddTable(New TableServiceSchema(tableName))
        Me.context.BeginSaveChanges(
            Sub(asyncResult)
                Try
                    Me.context.EndSaveChanges(asyncResult)
                    callback.Invoke(New CloudOperationResponse(Of String)(Nothing, Nothing))
                Catch exception As Exception
                    callback.Invoke(New CloudOperationResponse(Of String)(Nothing, StorageClientExceptionParser.ParseDataServiceException(exception)))
                End Try
            End Sub, Nothing)
    End Sub

    Public Sub CreateTableIfNotExist(ByVal tableName As String, ByVal callback As Action(Of CloudOperationResponse(Of Boolean))) Implements ICloudTableClient.CreateTableIfNotExist
        Me.DoesTableExist(
            tableName,
            Sub(tableExistsResult)
                If tableExistsResult.Exception IsNot Nothing OrElse tableExistsResult.Response Then
                    callback.Invoke(New CloudOperationResponse(Of Boolean)(False, tableExistsResult.Exception))
                Else
                    Me.CreateTable(
                        tableName,
                        Sub(tableCreateResult) callback.Invoke(New CloudOperationResponse(Of Boolean)(tableCreateResult.Exception Is Nothing, tableCreateResult.Exception)))
                End If
            End Sub)
    End Sub

    Public Sub DoesTableExist(ByVal tableName As String, ByVal callback As Action(Of CloudOperationResponse(Of Boolean))) Implements ICloudTableClient.DoesTableExist
        Dim uri = New Uri(String.Format(CultureInfo.InvariantCulture, "{0}/Tables?$filter=TableName eq '{1}'", Me.context.BaseUri.ToString().TrimEnd("/"c), tableName))

        Me.context.BeginExecute(Of TableServiceSchema)(
            uri,
            Sub(asyncResult)
                Try
                    Dim response = Me.context.EndExecute(Of TableServiceSchema)(asyncResult)
                    Dim responseList = TryCast(response, IEnumerable(Of TableServiceSchema))
                    Dim responseStatus = TryCast(response, OperationResponse)
                    callback.Invoke(New CloudOperationResponse(Of Boolean)((If(responseList IsNot Nothing, responseList.FirstOrDefault() IsNot Nothing, False)), (If(responseStatus IsNot Nothing, StorageClientExceptionParser.ParseDataServiceException(responseStatus.Error), Nothing))))
                Catch originalException As Exception
                    Dim dataServiceException = TryCast(originalException.GetBaseException(), DataServiceClientException)
                    If (dataServiceException IsNot Nothing) AndAlso (dataServiceException.StatusCode = 404) Then
                        callback.Invoke(New CloudOperationResponse(Of Boolean)(False, Nothing))
                    Else
                        callback.Invoke(New CloudOperationResponse(Of Boolean)(False, StorageClientExceptionParser.ParseDataServiceException(originalException)))
                    End If
                End Try
            End Sub,
            Nothing)
    End Sub
End Class
